<template>
  <pageHeader title="创建工单" :breadCrumb="['生产管理', '创建工单']" :show-back="true">
    <template #footer>
      <a-button @click="router.back()">取消</a-button>
      <a-button type="primary" @click="handleOk">保存</a-button>
    </template>
    <!-- 加载中 -->
    <a-spin :loading="loading" class="cantainer">
      <div class="tab">基础信息</div>
      <a-form :model="orderDate" auto-label-width class="form">
        <a-row :gutter="15">
          <a-col :span="12">
            <a-form-item label="关联生产订单">
              <a-input disabled :model-value="orderDate.number" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="物料编码">
              <a-input disabled :model-value="orderDate.material?.number" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="物料名称">
              <a-input disabled :model-value="orderDate.material?.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="规格型号">
              <a-input disabled :model-value="orderDate.material?.spec" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="需求数量">
              <a-input disabled :model-value="orderDate.planProduceNumber" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="已排数量">
              <a-input disabled :model-value="orderDate.quantityFilled" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="基本单位">
              <a-input disabled :model-value="orderDate.material?.basicUnit" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="关联生产BOM">
              <a-input disabled :model-value="orderDate.material?.bomCode" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="紧急等级">
              <a-select v-model:model-value="orderDate.emergencyLevel" disabled>
                <a-option v-for="(item, index) in ['一般', '紧急', '加急', '特急']" :value="index + 1" :key="index">
                  {{ item }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="工艺路线">
              <a-input disabled :model-value="orderDate.material?.productModel?.routerName" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="tab">工单信息</div>
      <a-form :model="formData" ref="refForm" class="form" auto-label-width>
        <a-row :gutter="15">
          <a-col :span="12">
            <a-form-item label="工单编号">
              <a-input placeholder="无需输入，系统自动生成..." disabled v-model="formData.workOrderCode" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="生产数量" field="produceNumber" :rules="getRules('生产数量')">
              <a-input-number :min="1" :max="orderDate.planProduceNumber - orderDate.quantityFilled" placeholder="请输入" v-model="formData.produceNumber" @change="produceNumberChange" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="计划人" field="plannerId" :rules="getRules('计划人')">
              <UserChoice v-model:value="formData.plannerId" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="创建人">
              <UserChoice v-model:value="formData.foundId" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="计划开工时间" field="startDate" :rules="getRules('计划开工时间')">
              <a-date-picker show-time format="YYYY-MM-DD HH:mm" v-model="formData.startDate" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="计划结束时间" field="endDate" :rules="getRules('计划结束时间')">
              <a-date-picker show-time format="YYYY-MM-DD HH:mm" v-model="formData.endDate" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="备注">
              <a-textarea placeholder="请输入" v-model="formData.remark" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <a-table v-model:expanded-keys="expandedKeys" stripe :pagination="false" :data="sonTree" row-key="id">
        <template #columns>
          <a-table-column v-for="header in herders" :key="header.name" :width="header.width || 200" :title="header.name" :data-index="header.code" align="center">
            <template #cell="{ record }" v-if="!header.code">
              <template v-if="header.name === '材料属性'">
                <a-select disabled :model-value="record.bomData?.management?.attribute">
                  <a-option :value="1">自制</a-option>
                  <a-option :value="2">委外</a-option>
                  <a-option :value="3">虚拟</a-option>
                  <a-option :value="4">采购</a-option>
                </a-select>
              </template>
            </template>
          </a-table-column>
          <a-table-column title="生产数量" fixed="right" :width="150">
            <template #cell="{ record }">
              <a-input-number :min="1" placeholder="请输入" disabled v-model="record.produceNumber" />
            </template>
          </a-table-column>
          <a-table-column :width="200" fixed="right" title="计划开工时间">
            <template #cell="{ record }">
              <a-date-picker show-time format="YYYY-MM-DD HH:mm" value-format="Date" v-model="record.startDate" />
            </template>
          </a-table-column>
          <a-table-column :width="200" fixed="right" title="计划完工时间">
            <template #cell="{ record }">
              <a-date-picker show-time format="YYYY-MM-DD HH:mm" value-format="Date" v-model="record.endDate" />
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-spin>
  </pageHeader>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref, computed } from 'vue';
import {
  EditProductBom,
  GetProductBomTree,
  GetProductBomByIds,
  ChangeProductProcessRoutState,
} from '@/api/FactoryModeling';
import { PutProduceOrderStatus } from '@/api/produce-management/produce-list/index';
import { GetProduceOrderDetails } from '@/api/produce-management/produce-list/index';
import type { TworkOrder } from '@/api/produce-management/OrderPlanning/type';
import { AddWorkOrders } from '@/api/produce-management/OrderPlanning';
import { useRoute, useRouter } from 'vue-router';
import Dayjs from 'dayjs';
import { Message } from '@arco-design/web-vue';

let route = useRoute();
let router = useRouter();
let loading = ref(false);
let orderDate = reactive<any>({});
let formData = reactive<TworkOrder>({});
let sonTree = ref<TworkOrder[]>([]);
let refForm = ref();
// 保存生产工单
let handleOk = async () => {
  try {
    if (!orderDate.material?.productModel?.id) {
      return Message.warning('请先为该物料配置工艺路线');
    }
    if (await refForm.value.validate()) return;
    let { planProduceNumber, id } = orderDate;
    let { foundId, plannerId, remark } = formData;
    let formList: TworkOrder[] = [
      {
        ...formData,
        totalNumber: planProduceNumber,
        produceOrderId: id,
        foundId,
        plannerId,
        remark,
        processRouteId: orderDate.material?.productModel?.id,
        endDate: Dayjs(formData.endDate).toJSON(),
        startDate: Dayjs(formData.startDate).toJSON(),
      },
    ];
    let isErr = false;
    let loadList = (setList: TworkOrder[]) => {
      setList.forEach(
        ({ productId, startDate, produceNumber, children }, index) => {
          // if(!planProduceNumber)Message.error('')
          formList.push({
            productId,
            endDate: Dayjs(startDate).toJSON(),
            startDate: Dayjs(startDate).toJSON(),
            produceNumber,
            totalNumber: planProduceNumber,
            produceOrderId: id,
            foundId,
            plannerId,
            remark,
          });
          loadList(children || []);
        }
      );
    };
    loadList(sonTree.value);
    PutProduceOrderStatus({ id: orderDate.id, status: 2 });
    ChangeProductProcessRoutState(orderDate.material?.productModel?.id);

    await AddWorkOrders({
      workOrderData: formList,
      id: orderDate.id,
      orderNumber: formData.produceNumber,
      totality: orderDate.planProduceNumber,
    });
    router.back();
  } catch (err) {
    console.log(err);
  }
};

let expandedKeys = ref<any>([]);
onMounted(async () => {
  loading.value = true;
  let type = route.query.type;
  try {
    if (type === 'add') {
      const res = await GetProduceOrderDetails({
        id: route.query.orderId,
      });
      Object.assign(orderDate, res);
      if (!orderDate.material?.productModel?.id) {
        Message.warning('请先为该物料配置工艺路线');
      }
      formData.productId = res.materialId;
      let tree = await GetProductBomTree(res.bomId);
      let ids: number[] = [];
      let ergodicFilterTree = (list: any[]) => {
        list.forEach(({ id, children }) => {
          if (id) ids.push(id);
          if (children) ergodicFilterTree(children);
        });
      };
      ergodicFilterTree([tree]);
      let childrenList = await GetProductBomByIds(ids);
      let loadChildren = (data: any, dosage: any, sonDosage: any) => {
        let bomData = childrenList.find(({ id }: any) => id === data.id);
        let magnification = Number(dosage) * Number(sonDosage);
        expandedKeys.value.push(data.id);
        return {
          ...data,
          productId: bomData.productId,
          magnification,
          bomData,
          children: data.children?.map((item: any) =>
            loadChildren(
              item,
              magnification,
              bomData?.productBomDetail?.find(
                ({ bomId }: any) => bomId === item.id
              )?.dosage || 1
            )
          ),
        };
      };
      let treeDate = loadChildren(tree, 1, 1);
      sonTree.value = treeDate.children || [];
      const deptDate = JSON.parse(sessionStorage.getItem('loginInfo') || '');
      formData.foundId = deptDate.id;
    }
  } catch (err) {
    console.error(err);
  }
  loading.value = false;
});

let produceNumberChange = () => {
  let num = formData.produceNumber || 0;
  let loadList = (list?: TworkOrder[]): TworkOrder[] =>
    list?.map((item) => {
      return {
        ...item,
        produceNumber: Number(item.magnification) * num,
        children: loadList(item.children),
      };
    }) || [];
  sonTree.value = loadList(sonTree.value);
};
// 表单校验
let getRules = (name?: string) => {
  return [{ required: true, message: (name || '') + '不能为空' }];
};

let herders = [
  { code: 'bomData.management.number', name: '产品编码' },
  { code: 'bomData.management.name', name: '产品名称' },
  { code: 'bomData.management.spec', name: '型号规格' },
  { name: '材料属性', width: 120 },
  { code: 'bomData.bomName', name: '生产BOM', width: 200 },
];
</script>

<style scoped lang="less">
.cantainer {
  padding: 20px;
  width: 100%;
}
.form {
  padding-left: 100px;
  padding-right: 100px;
}
.tab {
  border-left: 4px rgb(var(--arcoblue-6)) solid;
  padding-left: 20px;
  margin-bottom: 30px;
  font-size: 20px;
}
</style>
